package com.qdlc.p2p.biz.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.qdlc.p2p.biz.util.UserLoginUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dto.User;

public class SessionInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -2239644443711524657L;

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		User user = UserLoginUtil.getLoginUser();

		boolean newLogin = false;

		if (user == null) {
			// 判断是不是后台跳转到前台的，这种情况下，只要会话中还有
		    if (request.getParameter("borrowPreview") != null && request.getHeader("referer") != null) {
		        return actionInvocation.invoke();
		    }
			String servletPath = request.getServletPath();
			// 将action替换成html后缀
			servletPath = servletPath.replace(".action", ".html");
			String queryString = request.getQueryString();
			String redirectURL = servletPath;
			if (StringUtil.isNotBlank(queryString)) {
				redirectURL = request.getContextPath() + servletPath + "?" + StringUtil.isNull(queryString);
			}
			redirectURL = java.net.URLEncoder.encode(redirectURL, "UTF-8");
			String loginURl = "/user/login.html";
			String web_url = SystemConfigHelper.getValue(Nid.WEB_URL);
			if (newLogin) {
				response.sendRedirect(web_url + loginURl + "?newlogin=1&redirectURL="
						+ request.getContextPath() + redirectURL);
			} else {
				response.sendRedirect(web_url + loginURl + "?timeout=1&redirectURL="
						+ request.getContextPath() + redirectURL);
			}
			return null;
		}
		return actionInvocation.invoke();
	}

}
